﻿using System;
using System.Collections.Generic;
using System.Linq;
using TeF.Runner.Helpers;

namespace TeF.Runner
{
    internal class TestNamespace : TestStateEntityBase, ITestNamespace, ITestEntityChildOfT<TestAssembly, TestNamespace>, ITestEntityParentOfT<TestNamespace, TestContainer>
    {
        #region Fields

        private readonly TestParentHelper<TestNamespace, TestContainer> _testParentHelper;
        private readonly string _name;

        #endregion


        #region Constructors

        public TestNamespace(string name, bool ignored, TestAssembly testAssembly)
            : base(ignored)
        {
            if (string.IsNullOrWhiteSpace(name))
                throw new ArgumentException("name");
            if (testAssembly == null)
                throw new ArgumentNullException("testAssembly");
            
            _name = name;

            Parent = testAssembly;

            _testParentHelper = new TestParentHelper<TestNamespace, TestContainer>(this);
        }
        
        #endregion


        #region Properties

        public override string Name
        {
            get { return _name; }
        }
        
        public TestAssembly Parent { get; private set; }

        public ITestAssembly Assembly
        {
            get { return Parent; }
        }

        public IEnumerable<ITestContainer> Containers
        {
            get { return _testParentHelper.Children; }
        }

        public IEnumerable<TestContainer> Children
        {
            get { return _testParentHelper.Children; }
        }

        #endregion


        #region Public Methods

        public void AddChild(TestContainer child)
        {
            _testParentHelper.AddChild(child);
        }

        public void Dispose()
        {
            _testParentHelper.Dispose();
        }

        public IEnumerable<Test> GetTestsToRun()
        {
            if (Ignored)
                return new Test[] { };

            return
                _testParentHelper.Children
                    .Where(c => !c.Ignored)
                    .SelectMany(c => c.GetTestsToRun());

        }

        #endregion
    }
}
